<%--
  Created by IntelliJ IDEA.
  User: enjoy
  Date: 2020/6/6
  Time: 16:40
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>购物车</title>
    <link rel="stylesheet" href="css/bootstrap.min.css" />
    <link rel="stylesheet" href="css/font-awesome.css" />
    <script src="js/vue.js"></script>
    <script src="js/vendor/jquery-1.12.4.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/jquery.cookie.min.js"></script>
</head>
<style>
    * {
        margin: 0;
        padding: 0;
    }
    body {
        background-color: #EEEEEE;
    }
    .navbar-text a  {
        color: #ffffff;
    }
    .login-text {
        margin-right: 50px;
    }
    .logo {
        color: #E94F4C;
        font-size: 35px;
        display: inline-block;
    }
    .search-box {
        height: 48px;
    }
    .input-group-addon {
        background-color:#E94F4C;
        border: none;
        color: #ffffff;
    }
    .control-icon {
        position: absolute;
        top: 50%;
    }
    .mgt38 {
        margin-top: 30px;
    }
    .thumbnail a img {
        height: 200px;
        width: 200px;
    }
    .thumbnail .description {
        height: 40px;
        overflow: hidden;
    }
    a:hover {
        text-decoration: none;
    }
    h3, p {
        text-align: center;
    }
    table tr {
        background-color: #ffffff;
    }
</style>
<body>
<nav class="navbar navbar-default navbar-inverse navbar-static-top">
    <div class="container-fluid">
        <div class="navbar-header">
            <a href="index.jsp" class="navbar-brand" style="color: #ffffff;"><i class="fa fa-sign-language"></i> 寻欢易购</a>
        </div>
        <p class="navbar-text navbar-right login-text">
            <a id="loginText" href="login.jsp">登录</a>
        </p>
        <p class="navbar-text navbar-right">
            <a href="register.jsp">注册</a>
        </p>
    </div>
</nav>
<div class="container-fluid">
    <div class="row">
        <div class="col-xs-8 col-xs-push-2">
            <table id="app" class="table">
                <thead>
                <tr>
                    <td>商品</td>
                    <td>单价</td>
                    <td>数量</td>
                    <td>小计</td>
                    <td>操作</td>
                </tr>
                </thead>
                <tbody>
                <!--
                    如果没有商品，就是显示。
                -->
                <tr v-if="totalNum < 1">
                    <td colspan="5">暂无商品.<a href="index.jsp">去购物</a></td>
                </tr>
                <tr v-if="totalNum > 0" v-for="g in goods">
                    <td style="max-width: 200px;">
                        <div class="media">
                            <div class="media-left">
                                <a href="javascript: void(0);">
                                    <img class="media-object" height="80px" width="80px" :src='"http://localhost/"+g.smallPic'>
                                </a>
                            </div>
                            <div class="media-body">
                                <h4 class="media-heading">{{g.title}}</h4>
                            </div>
                        </div>
                    </td>
                    <td>{{g.price}}</td>
                    <td>

                        <div class="input-group" style="width: 150px;">

                            <span v-if="g.num == 1" style="background-color: #e2e2e2;" class="input-group-addon">-</span>

                             <span v-else @click="reduceGoodNum(g.goodsId)" class="input-group-addon" style="cursor: pointer;">-</span>

                            <input class="form-control" v-model="g.num">

                            <span @click="addGoodNum(g.goodsId)" class="input-group-addon" style="cursor: pointer;">+</span>
                        </div>
                    </td>
                    <td>{{g.subTotal}}</td>
                    <td>
                        <button @click="deleteSpecifyGood(g.goodsId)" class="btn btn-default">删除</button>
                    </td>
                </tr>
                </tbody>
                <tfoot>
                <tr v-if="goods.length != 0">
                    <td colspan="5">
                        已选购 <span style="color: red;">{{totalNum}}</span> 件商品,
                        总价 <span style="color: red;" id="totalPrice">{{totalPrice}}</span>
                        <button onclick="gotoSettleCount()" class="btn btn-danger btn-lg" style="float: right">去结算</button>
                    </td>
                </tr>
                </tfoot>
            </table>
        </div>
    </div>
</div>
</body>
<script>
    if (sessionStorage.getItem("userId") != null){
        console.log("登录状态")
    } else {
        console.log("未登录状态")
    }

    function gotoSettleCount(){
        window.location.href = 'paymentPage.jsp';
    }

    $(document).ready(function () {
        var item = localStorage.getItem("local_goods_cart");
        if (item != null){
            var goodsIds = Object.keys(JSON.parse(item)).join(',');
        }


        //获取页面数据交给Vue对象
        $.ajax({
            url: "cartServlet",
            type: "POST",
            data: {
                method: "getGoodsByIds",
                goodsIds: goodsIds
            },
            dataType: "json",
            success: function (data) {

                var goodsCart = JSON.parse(localStorage.getItem("local_goods_cart"));

                var totalNum = 0;
                var totalPrice = 0;

                //将对象赋值给Vue使用
                for (var i = 0; i < data.length; i++) {
                    var mov = data[i];

                    var smallPic = mov.smallPic;
                    var title = mov.title;
                    var price = mov.price;
                    var num = goodsCart['' + mov.goodsId];
                    var subTotal = num * price;
                    var goodsId = mov.goodsId;
                    totalNum += num;
                    totalPrice += subTotal;

                    vm.goods.push({
                        smallPic: smallPic,
                        title: title,
                        price: price,
                        num: num,
                        subTotal: subTotal,
                        goodsId: goodsId
                    });

                }

                vm.totalNum = totalNum;
                vm.totalPrice = totalPrice;

            }

        });
        //Vue渲染页面
        var vm = new Vue({
            el: '#app',
            data: {
                goods: [],
                totalNum: 0,
                totalPrice: 0
            },
            methods: {
                //减少购物车中某商品的数量
                reduceGoodNum: function (goodsId) {

                    var goodsCart = JSON.parse(localStorage.getItem("local_goods_cart"));
                    goodsCart[goodsId]--;

                    localStorage.setItem("local_goods_cart", JSON.stringify(goodsCart));

                    if (sessionStorage.getItem("userId") != null){
                        updateGoods4Cart(goodsId);
                        sysnGoodsCart(goodsCart);
                    }

                    reNum(goodsId);

                },
                //增加购物车中某商品的数量
                addGoodNum: function (goodsId) {

                    var goodsCart = JSON.parse(localStorage.getItem("local_goods_cart"));
                    goodsCart[goodsId]++;

                    localStorage.setItem("local_goods_cart", JSON.stringify(goodsCart));

                    if (sessionStorage.getItem("userId") != null){
                        updateGoods4Cart(goodsId);
                        sysnGoodsCart(goodsCart);
                    }

                    reNum(goodsId);

                },
                //删除购物车中的某个商品
                deleteSpecifyGood: function (goodsId) {

                    goodsId = goodsId+'';

                    var goodsCart = JSON.parse(localStorage.getItem("local_goods_cart"));

                    delete goodsCart[goodsId];

                    localStorage.setItem("local_goods_cart", JSON.stringify(goodsCart));

                    if (sessionStorage.getItem("userId") != null){
                        deleteCartData(goodsId);
                        sysnGoodsCart(goodsCart);
                    }

                    //删除Vue对象中的信息
                    var goods = vm.goods;

                    for (var i = 0; i < goods.length; i++) {
                        if (goodsId == goods[i].goodsId){
                            goods.splice(i, 1);
                        }
                    }

                    var totalNum = 0;
                    var totalPrice = 0;
                    for (var i = 0; i < goods.length; i++) {
                        totalNum += goods[i].num;
                        totalPrice += goods[i].subTotal;
                    }
                    vm.totalNum = totalNum;
                    vm.totalPrice = totalPrice;

                }
            }
        });


        //加减商品数量后更新Vue对象的数据
        function reNum(goodsId) {
            goodsId = Number(goodsId);
            var goodsCart = JSON.parse(localStorage.getItem("local_goods_cart"));
            vm.totalNum = 0;
            vm.totalPrice = 0;

            for (var i = 0; i < vm.goods.length; i++) {
                if (vm.goods[i].goodsId == goodsId) {
                    vm.goods[i].num = goodsCart[goodsId + ''];
                    vm.goods[i].subTotal = vm.goods[i].num * vm.goods[i].price;
                }

                vm.totalNum += vm.goods[i].num;
                vm.totalPrice += vm.goods[i].subTotal;
            }
        };

        function updateGoods4Cart(goodsId) {
            var number = JSON.parse(localStorage.getItem("local_goods_cart"))[goodsId];
            $.ajax({
                url: "cartServlet",
                type: "post",
                data: {
                    method: "updateGoods4Cart",
                    userId: sessionStorage.getItem("userId"),
                    goodsId: goodsId,
                    num: number
                }
            });
        }

        function deleteCartData(goodsId) {
            $.ajax({
                url: "cartServlet",
                type: "post",
                data: {
                    method: "deleteCartData",
                    userId: sessionStorage.getItem("userId"),
                    goodsId: goodsId
                }
            });
    }

        //同步购物车
        function sysnGoodsCart(goodsCart) {
        $.ajax({
            url: "cartServlet",
            type: "post",
            data: {
                method: "syncGoodsCart",
                cartData: goodsCart
            },
            dataType: "json",
            //  data含有合并购物车的集合， 合并后要将localStorage更新
            success: function (data) {
                localStorage.clear();
                localStorage.setItem("local_goods_cart",JSON.stringify(data.map));
            }
        });
    }


    });
</script>
</html>
